// create package.json, README, etc. for packages that don't have them yet

const fs = require('fs')
const path = require('path')
const args = require('minimist')(process.argv.slice(2))
const { packages, pkg } = require('./util')

const target = args._.length ? args._[0] : ''

if (!target) {
  throw new Error('The package name is empty')
}
const targetDir = path.join(packages, target)
if (fs.existsSync(targetDir)) {
  throw new Error('The package name is already exists')
}
const isPrivate = args.p
fs.mkdirSync(targetDir)
const newDir = ['src', '__tests__', 'example']
newDir.forEach(d => fs.mkdirSync(path.join(targetDir, d)))

const json = {
  name: `@lin/${target}`,
  version: '1.0.0', // 初始化的版本都是 1.0.0
  description: `@lin/${target}`,
  main: 'index.ts',
  module: `dist/${target}.esm.js`,
  types: `dist/${target}.d.ts`,
  files: [`index.js`, `dist`],
  repository: Object.assign(pkg.repository, {
    directory: `packages/${target}`
  }),
  keywords: ['wheel', target],
  author: 'lin',
  license: pkg.license,
  dependencies: {
    '@lin/common': '1.0.0'
  }
}
if (isPrivate) json.private = true

fs.writeFileSync(
  path.join(targetDir, 'package.json'),
  JSON.stringify(json, null, 2)
)

fs.writeFileSync(
  path.join(targetDir, 'README.md'),
  `# ${target}\n\n模拟 ${target} 原理\n`
)
fs.writeFileSync(path.join(targetDir, `src/index.ts`), '')
fs.writeFileSync(
  path.join(targetDir, `index.js`),
  `
'use strict'
module.exports = require('./dist/${target}.umd.js')
`.trim() + '\n'
)
fs.writeFileSync(
  path.join(targetDir, 'example/index.html'),
  `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${target}</title>
  <script src="/dist/${target}.umd.js"></script>
</head>
<body>
</body>
</html>
`
)
